package com.gjq.springboot.server;

import com.gjq.springboot.config.SftpConnectConfig;
import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.util.*;


@Service
@Slf4j
@PropertySource("classpath:application.yml")
public class SftpFileService {

//    @Resource
    private ChannelSftp channelSftp;

    @Autowired
    private SftpConnectConfig sftpConnectConfig;

    public int connectSftp() throws  InterruptedException {
        while (sftpConnectConfig.getHost() == null) {
            System.out.println("Host is not set");
            Thread.sleep(1000);
        }
        this.channelSftp = sftpConnectConfig.channelSftp();
        if(this.channelSftp == null) return 0;
        return 1;
    }

    //打开路径
    @Value("${remoteserver.path}")
    private  String FTP_BASEPATH;

    /**
     * 从服务器获取文件并返回字节数组
     * @param path 要下载文件的路径
     * @param file 要下载的文件
     */
    public byte[] download(String path, String file) throws Exception {
        // 切换到文件所在目录
        channelSftp.cd(path);
        //获取文件并返回给输入流,若文件不存在该方法会抛出常
        InputStream is = channelSftp.get(file);
        //ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] fileData = IOUtils.toByteArray(is);
        if(is != null){
            is.close();
        }
        return fileData;
    }

    public boolean upload(@RequestParam("file") MultipartFile uploadFile, @RequestParam("selectIndex") String path) throws Exception{
        if(path == null) path = FTP_BASEPATH;
        String fileName = uploadFile.getOriginalFilename();
        int len = fileName.length();
        for(int i=0;i<len;i++){
            if(fileName.charAt(i)==' ') return false;
        }
        // 用uuid + 原来的文件名生成新名字，防止文件名重复也可以辨识上传的文件是哪个,可以省略这一步
        //String newName = UUID.randomUUID().toString().replaceAll("-","") + fileName;
        String newName = fileName;
        List<com.gjq.springboot.entity.File> Files = (List<com.gjq.springboot.entity.File>) getFileList(path);
        newName = addWei(Files, fileName);
        File file = new File(path + newName);
        //将MultipartFilez转换为File，会生成文件
        FileUtils.copyInputStreamToFile(uploadFile.getInputStream(), file);
        // 如果该目录不存在则直接创建新的目录，并切换到该目录
        try {
            channelSftp.cd(path);
        } catch (Exception e) {
            channelSftp.mkdir(path);
            channelSftp.cd(path);
        }
        channelSftp.put(new FileInputStream(file), newName);
        // 操作完成，删除刚刚生成的文件
        file.delete();
        return true;
    }

    public Object getFileList(String path) {
        System.out.println("FTP_BASEPATH "+FTP_BASEPATH);
        if(path == null) path = FTP_BASEPATH;
        try {
            Vector ls = channelSftp.ls(path);
            int len = ls.size();
            List<com.gjq.springboot.entity.File> Files = new ArrayList<>();
            for(int i = 2;i < len;i++){
                com.gjq.springboot.entity.File file2 = new com.gjq.springboot.entity.File();
                String str = ls.get(i) + "";
//                System.out.println(str);
                String[] arr = str.split("\\s+");
                String name = arr[arr.length - 1];
                String time = arr[arr.length - 4] + " " + arr[arr.length - 3] + " " + arr[arr.length - 2];
                int size = Integer.parseInt(arr[arr.length - 5]);
                String type = arr[arr.length - 9];
                if (type.charAt(0) == '-'){
                    file2.setType(1);
                }else file2.setType(2);
                file2.setFilename(name);
                file2.setCreatTime(time);
                file2.setSize(size);
                file2.setPath(path);
                Files.add(file2);
                //file2.setPath(channelSftp.pwd());
            }
//            Collections.sort(Files, new Comparator<com.gjq.springboot.entity.File>() {
//                @Override
//                public int compare(com.gjq.springboot.entity.File f1, com.gjq.springboot.entity.File f2) {
//                    return f2.getCreatTime().compareTo(f1.getCreatTime());
//                }
//            });
            //文件排序
//            Collections.sort(Files, new Comparator<com.gjq.springboot.entity.File>() {
//                @Override
//                public int compare(com.gjq.springboot.entity.File f1, com.gjq.springboot.entity.File f2) {
//                    String[] months = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
//                    String f1Month = f1.getCreatTime().split(" ")[0];
//                    String f2Month = f2.getCreatTime().split(" ")[0];
//                    int f1MonthIndex = Arrays.asList(months).indexOf(f1Month);
//                    int f2MonthIndex = Arrays.asList(months).indexOf(f2Month);
//                    if (f1MonthIndex < f2MonthIndex) {
//                        return 1;
//                    } else if (f1MonthIndex > f2MonthIndex) {
//                        return -1;
//                    } else {
//                        return f2.getCreatTime().compareTo(f1.getCreatTime());
//                    }
//                }
//            });
            Collections.sort(Files, new Comparator<com.gjq.springboot.entity.File>() {
                @Override
                public int compare(com.gjq.springboot.entity.File f1, com.gjq.springboot.entity.File f2) {
                    String[] months = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
                    String f1Month = f1.getCreatTime().split(" ")[0];
                    String f2Month = f2.getCreatTime().split(" ")[0];
                    int f1MonthIndex = Arrays.asList(months).indexOf(f1Month);
                    int f2MonthIndex = Arrays.asList(months).indexOf(f2Month);
                    if (f1MonthIndex < f2MonthIndex) {
                        return 1;
                    } else if (f1MonthIndex > f2MonthIndex) {
                        return -1;
                    } else {
                        //return f2.getCreatTime().compareTo(f1.getCreatTime());
                        String data1 = f1.getCreatTime().split(" ")[1];
                        int data11 = Integer.valueOf(data1);
                        String data2 = f2.getCreatTime().split(" ")[1];
                        int data22 = Integer.valueOf(data2);
                        if(data11<data22){
                            return 1;
                        }else if(data11>data22){
                            return -1;
                        }
                        else{
                            String hour1 = f1.getCreatTime().split(" ")[2].split(":")[0];
                            String hour2 = f2.getCreatTime().split(" ")[2].split(":")[0];
                            int hour11 = Integer.valueOf(hour1);
                            int hour22 = Integer.valueOf(hour2);
                            if(hour11<hour22){
                                return 1;
                            }else if(hour11>hour22){
                                return -1;
                            }else{
                                return 0;
                            }
                        }
                    }
                }
            });
            //时间复杂度过高
//            Collections.sort(Files, new Comparator<com.gjq.springboot.entity.File>() {
//                @Override
//                public int compare(com.gjq.springboot.entity.File f1, com.gjq.springboot.entity.File f2) {
//                    String[] months = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
//                    String f1Month = f1.getCreatTime().split(" ")[0];
//                    String f2Month = f2.getCreatTime().split(" ")[0];
//                    int f1MonthIndex = Arrays.asList(months).indexOf(f1Month);
//                    int f2MonthIndex = Arrays.asList(months).indexOf(f2Month);
//                    if (f1MonthIndex != f2MonthIndex) {
//                        return Integer.compare(f2MonthIndex, f1MonthIndex);
//                    } else {
//                        String[] f1Time = f1.getCreatTime().split(" ")[1].split(":");
//                        String[] f2Time = f2.getCreatTime().split(" ")[1].split(":");
////                        for(String s: f1Time){
////                            System.out.println(s);
////                        }
//                        int f1Hour = Integer.parseInt(f1Time[0]);
//
//                        int f2Hour = Integer.parseInt(f2Time[0]);
//                        if (f1Hour != f2Hour) {
//
//                            return Integer.compare(f2Hour, f1Hour);
//                        } else {
//                            int f1Minute = Integer.parseInt(f1Time[1]);
//                            int f2Minute = Integer.parseInt(f2Time[1]);
//                            if (f1Minute != f2Minute) {
//                                return Integer.compare(f2Minute, f1Minute);
//                            } else {
//                                int f1Second = Integer.parseInt(f1Time[2]);
//                                int f2Second = Integer.parseInt(f2Time[2]);
//                                return Integer.compare(f2Second, f1Second);
//                            }
//                        }
//                    }
//                }
//            });

            return Files;

        } catch (SftpException e) {
            e.printStackTrace();
        }
        return false;
    }
    //新建文件夹
    public  boolean addFolder(String filename, String path){
        String folder = path + "/" + filename;
        try {
            channelSftp.mkdir(folder);
            return true;
        } catch (SftpException e) {
            e.printStackTrace();
        }
        return false;
    }
    //重名文件处理
    public static String addWei(List<com.gjq.springboot.entity.File> ftpFiles, String originFileName){
        for (com.gjq.springboot.entity.File ftpFile : ftpFiles){
            if(originFileName.equals(ftpFile.getFilename())){
                //System.out.println("3 "+originFileName);
                //同名文件 递归
                String filename = ftpFile.getFilename();
                String suffix = filename.substring(filename.lastIndexOf("."));
                String forth = filename.substring(0,filename.lastIndexOf("."));
                if(forth.length()<4){
                    originFileName = forth +"(1)"+suffix;
                    return addWei(ftpFiles, originFileName);
                }else{
                    String wei = forth.substring(forth.length()-3, forth.length());
                    String qian = forth.substring(0, forth.length()-3);
                    //System.out.println(wei);
                    //System.out.println(qian);
                    if(wei.charAt(0) == '(' && wei.charAt(2) == ')'){
                        int time = Integer.valueOf(wei.charAt(1)) - 48;
                        System.out.println("time"+time);
                        time++;
                        wei = "(" + time +")";
                        originFileName = qian + wei +suffix;
                        System.out.println("2 "+originFileName);
                        return addWei(ftpFiles, originFileName);
                    }else{
                        originFileName = forth +"(1)"+suffix;
                        System.out.println("(1)");
                        return addWei(ftpFiles, originFileName);
                    }
                }
            }
        }
        //System.out.println("final_qian "+originFileName);
        return originFileName;
    }
}
